<template>
  <div class="geo-coding-demo">
    <el-input v-model="address" placeholder="请输入地址"></el-input>
    <el-button type="primary" @click="getLocation">查询位置</el-button>
    <div v-if="resultVisible">
      <p>城市: {{ location.city }}</p>
      <p>区县: {{ location.district }}</p>
      <p>经度: {{ location.lng }}</p>
      <p>纬度: {{ location.lat }}</p>
    </div>
    <el-alert v-if="errorMessage" :title="errorMessage" type="error" show-icon></el-alert>
  </div>
</template>

<script>
export default {
  data() {
    return {
      address: '',
      location: {},
      resultVisible: false,
      apiKey: '8c203af36966473b4b4180ad8a68a43b', // 替换为你的实际API Key
      errorMessage: ''
    };
  },
  methods: {
    getLocation() {
      this.errorMessage = ''; // 清除之前的错误信息
      const url = `https://restapi.amap.com/v3/geocode/geo?address=${encodeURIComponent(this.address)}&key=${this.apiKey}`;
      fetch(url)
        .then(response => response.json())
        .then(data => {
          if (data.status === '1' && data.geocodes.length > 0) {
            const geoCode = data.geocodes[0];
            this.location = {
              city: geoCode.city || '未知',
              district: geoCode.district || '未知',
              lng: geoCode.location.split(',')[0],
              lat: geoCode.location.split(',')[1]
            };
            this.resultVisible = true;
          } else {
            this.errorMessage = '无法获取地理位置信息';
            console.error('Geocoding failed:', data);
          }
        })
        .catch(error => {
          this.errorMessage = '请求出错';
          console.error('Error fetching geocoding data:', error);
        });
    }
  }
};
</script>

<style scoped>
.geo-coding-demo {
  padding: 20px;
}
</style>